package cloud.pangui.core.mongo.operate;

import cloud.pangui.core.mongo.utils.SqlWhereParseUtils;

/**
 * 使用sql语句删除
 * @Auther hepangui
 * @Date 2020/10/06 0001
*/
public class SqlDelete extends Delete {

	SqlDelete(String sql) {
		this.build(sql);
	}

	/**
	 * 根据sql语句构建delete
	 * @return
	 */
	public Delete build(String sql) {
		String sqlCopy = sql.replaceAll("\n|\t|\r|\n\r", " ");
		String sqlUpper = sqlCopy.toUpperCase();
		int whereBegin = sqlUpper.indexOf(" WHERE ");
		String tableStr;
		if(sqlUpper.indexOf(" FROM ")>-1){
			int deleteBegin = sqlUpper.indexOf(" FROM ");
			 tableStr = sqlCopy.substring(deleteBegin + " FROM ".length(), whereBegin > -1 ? whereBegin : sqlCopy.length());
		}else{
			int deleteBegin = sqlUpper.indexOf("DELETE ");
			tableStr = sqlCopy.substring(deleteBegin + "DELETE ".length(), whereBegin > -1 ? whereBegin : sqlCopy.length());
		}

		this.collectionName = tableStr.trim();
		if (whereBegin != -1) {
			String whereSql = sqlCopy.substring(whereBegin + " WHERE ".length());
			this.where(SqlWhereParseUtils.parseWhere(whereSql,Where.SIMPLE_MODE));
		}
		return this;
	}
}
